package net.mingsoft.dashboard.biz.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import net.mingsoft.basic.core.SessionContext;
import net.mingsoft.basic.util.DateUtil;
import net.mingsoft.basic.util.SqlUtil;
import net.mingsoft.dashboard.action.q.collection.CollectionCreateQuery;
import net.mingsoft.dashboard.action.q.collection.CollectionDeleteQuery;
import net.mingsoft.dashboard.action.q.collection.CollectionListQuery;
import net.mingsoft.dashboard.action.q.collection.CollectionModifyQuery;
import net.mingsoft.dashboard.action.r.CollectionDirResponse;
import net.mingsoft.dashboard.action.r.CreateOrModifyCollectionResponse;
import net.mingsoft.dashboard.action.r.FileCollectionResponse;
import net.mingsoft.dashboard.biz.MyCollectionBiz;
import net.mingsoft.dashboard.dao.CollectionDao;
import net.mingsoft.dashboard.entity.collection.FileCollectionEntity;
import net.mingsoft.document.constant.FileConstant;
import net.mingsoft.document.util.FileTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gengfa
 * @date 22/02/10
 */
@Service
@Slf4j
public class MyCollectionBizImpl implements MyCollectionBiz {
    @Resource
    CollectionDao collectionDao;

    private static final String STATUS_DELETED = "DELETED";

    private static final String DEFAULT_NAME = "默认收藏夹";

    @Override
    public CreateOrModifyCollectionResponse createCollection(CollectionCreateQuery query) {
        CreateOrModifyCollectionResponse response = new CreateOrModifyCollectionResponse();
        if (null != getEntity(query.getName())) {
            return response.setExists(true);
        }

        FileCollectionEntity e = new FileCollectionEntity()
                .setName(query.getName())
                .setCreatedBy(SessionContext.session().getId())
                .setCreatedDate(DateUtil.now())
                .setUserId(SessionContext.session().getIntegerId());

        if (1 == collectionDao.insertOne(e)) {
            return response.setExists(false).setId(e.getId());
        }

        return response;
    }

    public FileCollectionEntity getEntity(String name) {
        return collectionDao.selectByName(name, SessionContext.session().getIntegerId());
    }

    @Override
    public CreateOrModifyCollectionResponse modifyName(CollectionModifyQuery query) {
        CreateOrModifyCollectionResponse response = new CreateOrModifyCollectionResponse();
        if (null != getEntity(query.getCollectionName())) {
            return response.setExists(true);
        }

        if (1 == collectionDao.updateName(query)) {
            return response.setId(query.getCollectionId()).setExists(false);
        }

        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleted(CollectionDeleteQuery query) {
        try {
            int effectedRows = 0;

            for (Long id : query.getCollectionId()) {
                effectedRows += collectionDao.updateStatus(id, STATUS_DELETED);
            }

            if (effectedRows != CollectionUtils.size(query.getCollectionId())) {
                throw new Exception("deleted failed");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    public List<CollectionDirResponse> dir() {
        List<CollectionDirResponse> dirResponses = collectionDao.selectAllDir(SessionContext.session().getIntegerId());
        if (CollectionUtils.isEmpty(dirResponses)) {
            createCollection(new CollectionCreateQuery().setName(DEFAULT_NAME));
            dirResponses = collectionDao.selectAllDir(SessionContext.session().getIntegerId());
        }
        return dirResponses;
    }

    @Override
    public Page list(CollectionListQuery query) {
        Page page;
        if (StringUtils.isNotBlank(query.getCollectionName())) {
            query.setCollectionName(SqlUtil.likeStr(query.getCollectionName()));
        }

        if (StringUtils.isNotBlank(query.getFileName()) ||
                (query.getCollectionId() != null && query.getCollectionId() > 0)) {
            query.setFileName(SqlUtil.likeStr(query.getFileName()));
            Page<FileCollectionResponse> pageFile = collectionDao.selectStarFileListByUserId(
                    new Page<>(query.getPageNo(), query.getPageSize()),
                    SessionContext.session().getIntegerId(), query);
            pageFile.getRecords().forEach(it -> {
                @SuppressWarnings("all")
                final String ext = Files.getFileExtension(it.getFileName());
                it.setFileExt(ext).setFileType(FileTypeUtil.getType(ext));
                it.setFileUrl(it.getFilePath());
                it.setFilePath(getParentFilePath(it.getFilePath()));
            });
            page = pageFile;
        } else {
            page = collectionDao.selectListByUserId(
                    new Page<>(query.getPageNo(), query.getPageSize()),
                    SessionContext.session().getIntegerId(), query);
        }

        return page;
    }

    private String getParentFilePath(String filePath) {
        Path p = Paths.get(filePath);

        if (StringUtils.isBlank(p.toString())) {
            return File.separator;
        } else {
            if (p.getParent() == null || StringUtils.isBlank(p.getParent().toString())) {
                return File.separator;
            } else {
                return p.getParent().toString();
            }
        }
    }
}
